<?php
if(!isset($_COOKIE['hid'])){
    header('Location:index');
}elseif (isset ($_COOKIE['hid'])) {
    header('Location:welcome');
}
/*
 * This is to login to hospital module.
 */
include 'config.php';
/*
 * get password key.
 */
$key1 = mysql_fetch_array(mysql_query("select * from pro where name= 'passkey' ")) or die(mysql_error());
$key = $key1['value'];
/*
 * encryption technique
 */

function _encode($password, $key) {
    $majorsalt = null;
    if ($key != '') {
        $_password = $key . $password;
    } else {
        $_password = $password;
    }
    if (function_exists('str_split')) {
        $_pass = str_split($_password);
    } else {
        $_pass = array();
        if (is_string($_password)) {
            for ($i = 0; $i < strlen($_password); $i++) {
                array_push($_pass, $_password[$i]);
            }
        }
    }

    foreach ($_pass as $_hashpass) {
        $majorsalt .= md5($_hashpass);
    }
    return $password = md5($majorsalt);
}

/*
 * main logic
 */
$user_name = $_POST['user_name'];
$password = $_POST['password'];
$query = mysql_query("select * from fa_user where user_name = '$user_name' and banned= 0 ") or die(mysql_error());
if (mysql_num_rows($query) == 0) {
    $err = 'No Such a hospital or Banned.';
    //die($err);
    header('Location:index?err='.$err);
} else {
    while ($row = mysql_fetch_array($query)) {
        $real_pass = $row['password'];
        $hospital_id = $row['id'];
    }
    $password = _encode($password, $key);
    if($password==$real_pass){
        setcookie("hid", $hospital_id, time() + 3600, "/", "192.168.1.2");
    }else{
        $err = 'Invalid Password';
        //die($err);
        header('Location:index?err='.$err);
    }
}
?>
